package com.eschool.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.eschool.dao.ParentDao;
import com.eschool.dao.RoleDao;
import com.eschool.dao.StudentDao;
import com.eschool.dao.UserDao;
import com.eschool.model.Section;
import com.eschool.model.Student;
import com.eschool.model.User;
import com.eschool.service.AlertService;
import com.eschool.service.StudentService;
import com.eschool.util.UserUtil;

public class StudentServiceImpl implements StudentService {

	@Override
	public boolean addStudent(Student student) {

		student.getParent().getUser()
				.setAddress(student.getParent().getPresentAddress());
		student.getParent().getUser().setName(student.getParent().getName());
		student.getParent().getUser()
				.setPhoneNumber(student.getParent().getPhoneNumber());
		student.getParent().getUser()
				.setBranch(UserUtil.currentUser().getBranch());
		student.getParent().getUser()
				.setRole(RoleDao.getRoleByProperty("roleId", 3));

		if ((UserDao.getUserByProperty("email", student.getParent().getUser()
				.getEmail())) != null) {
			return false;
		}

		int userId = UserDao.addUser(student.getParent().getUser());

		if (userId == -1)
			return false;

		student.getParent().getUser().setUserId(userId);

		int parentId = ParentDao.addParent(student.getParent());

		if (parentId == -1)
			return false;

		AlertService service = new AlertServiceImpl();

		List<User> rec = new ArrayList<User>();
		rec.add(student.getParent().getUser());

		String message = "Your account has been created at JSMSC with following credentials.";
		message += "\n\t\tEmail: " + student.getParent().getUser().getEmail();
		message += "\n\tPasword: "
				+ student.getParent().getUser().getPassword();
		message += "\n\n\tUse "
				+ "http://localhost:8080/eSchool/faces/pages/customer/login.xhtml"
				+ " to login.";

		service.sendAlert("Account Creation", message, rec, null);

		student.getParent().setParentId(parentId);

		if (StudentDao.addStudent(student))
			return true;

		return false;
	}

	@Override
	public boolean updateStudentStatus(List<Student> students, boolean newStatus) {
		for (Iterator iterator = students.iterator(); iterator.hasNext();) {
			Student student = (Student) iterator.next();
			student.setCurrentStatus(newStatus);
			StudentDao.updateStudent(student);
		}

		return true;
	}

	@Override
	public boolean promoteStudent(List<Student> students, Section newClass) {
		for (Iterator iterator = students.iterator(); iterator.hasNext();) {
			Student student = (Student) iterator.next();
			StudentDao.promoteStudent(student, newClass);
		}

		return true;

	}

	@Override
	public List<Student> getAllStudents() {
		return StudentDao.getStudents(UserUtil.currentUser().getBranch().getBranchId());
	}

}
